# from email.mime import image
import io
import base64
from flask import Flask, request, render_template, send_file
import os
import numpy as np
from PIL import Image
import base64
from io import BytesIO

app = Flask(__name__)
from flask_cors import CORS
from detect import parse_opt, check_requirements,run

CORS(app, supports_credentials=True)


@app.route('/')  # 代表首页
def index():  # 视图函数
    # y=[]
    # x=1
    # y.append([x])
    return render_template('register.html')


@app.route("/encoder", methods=['POST'])
def encoder():
    try:
        image = request.files.get("file")
        model = request.values.get("model")
        image_path = os.path.join(os.path.dirname(__file__), "static", image.filename)
        image.save(image_path)  # 首先
        confThreshold = request.values.get("confThreshold")
        iouThreshold = request.values.get("iouThreshold")
        print(model)
        print(image_path)
        print(confThreshold)
        print(iouThreshold)
        opt = parse_opt(model_path=model, source=image_path, output_path='out_img',conf_thres=confThreshold,iou_thres=iouThreshold) # 配置参数
        check_requirements(exclude=('tensorboard', 'thop')) # 校验

        result = run(**vars(opt))
        print(result)
        # array = result.astype(np.uint8)  # 转换成无符号8位整型

        # 将NumPy数组转换成PIL图片对象
        image = Image.open(result)

        # 创建一个字节流
        buffer = BytesIO()

        # 将图片保存到字节流中，格式为PNG
        image.save(buffer, format="JPEG")

        # 获取字节流的内容
        img_str = buffer.getvalue()

        # 将字节流编码成base64字符串
        img_base64 = base64.b64encode(img_str)

        # 将base64编码的数据解码成字符串
        img_base64_str = img_base64.decode('utf-8')

        return img_base64_str
        # image_path = os.path.join(os.path.dirname(__file__), "static")
        # 解码base64数据
        # image_data = base64.b64decode(image)

        # image.save(image_path) # 首先
        # file = request.files.get("file")
        # file_path = os.path.join(os.path.dirname(__file__), "static", f"result_{predict.generate_random_str(10)}.jpg")
        # file.save(file_path)
    except Exception as e:
        print(e)
        return {
            "status": 0,
            "error": f"后端报错:{e}"
        }

app.config['DEBUG'] = True

if __name__ == '__main__':
    # 0.0.0.0代表任何能代表这台机器的地址都可以访问
    app.run(host='0.0.0.0', port=5000)  # 运行程序
    # http://8.133.188.11:5000/
